r'''
AUTHOR:           Haimeng Lan
CREATION DATE:    03/01/2024
LAST EEDITED:     03/01/2024
FUNCTION:         50ms Average Filter data for acceleration test
RUN METHOD:       1. install python3 
                  2. open powershell or terminal
                  3. run command: pip install matplotlib, pandas, openpyxl
                  4. run script: python "E:\蓝海梦\python\acceleration.py" "C:\Users\KS00620\Desktop\400hz-tip2SAHA2.xlsx"
                  (giving a folder path is surported, it will run all the xlsx files in the folder)
'''
# import numpy as np
import matplotlib.pyplot as plt
import pandas as pd # pip install openpyxl
import os, sys

# frequency = 400
# frequency = 1600
# frequency = 20000
frequency = int(input("input frequency: "))
window = int(0.050/(1/frequency))
print(f"frequency is {frequency} Hz, window is {window}")

def moving_average_filter(xlsx_path):
    df = pd.read_excel(xlsx_path, "Data1", skiprows=[1]) # skip the unit row
    df = df.dropna(axis=0) # delete empty line
    # geitting the moving average values
    moving_average = df["X"].rolling(window=window).mean()
    print(f"the filter average data count: {moving_average.size}")
    print(f"the maximum value of filter data: {moving_average.max()}")
    print(f"the minimum value of filter data: {moving_average.min()}")
    # draw picture
    my_fig = plt.figure()
    ax=my_fig.add_axes([0.1,0.1,0.8,0.8])
    ax.plot(df["Time"], moving_average)
    filename = os.path.splitext(os.path.basename(xlsx_path))[0]
    ax.set_title(f"{filename} 50ms Averaging Filter")
    ax.set_xlabel('Time(s)')
    ax.set_ylabel('X Acceleration(g)')
    ax.text(x=0, y=0.9, s= f"max:{moving_average.max():.3f}", fontsize=14, color="blue", transform=ax.transAxes)
    # plt.show()
    my_fig.savefig(os.path.join(os.path.dirname(xlsx_path), filename+".png"))

if __name__=="__main__":
    path = sys.argv[1] 
    if os.path.isdir(path):
        for cur, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(".xlsx"):
                    try:
                        print(f"start running {os.path.join(cur, file)}")
                        moving_average_filter(os.path.join(cur, file))
                        print("successed\n")
                    except Exception as e:
                        print(f"failed, {e}")
    else:
        if path.endswith(".xlsx"):
            moving_average_filter(path)
            
